package v1

import (
	"errors"
	"gitee.com/CrazyMage/lite-note/internal/controller/http/v1/request"
	"gitee.com/CrazyMage/lite-note/internal/controller/http/v1/response"
	"gitee.com/CrazyMage/lite-note/pkg/utils"
	"github.com/gin-gonic/gin"
	"strings"
)

// registerHandler
// @Summary      用户注册
// @Description  通过用户名和密码注册
// @Tags         USER
// @Accept       json
// @Produce      json
// @Param        req  body      request.RegisterReq  true  "用户信息（JSON格式）"
// @Success      200   {object}  response.Response "{"code": 200,"data": {}, "message": "成功"}"
// @Failure      500   {object}  response.Response "{"code": 500,"data": {}, "message": "用户已存在"}"
// @Router       /v1/user/register [post]
func (r *V1) registerHandler(ctx *gin.Context) {

	//1.请求参数
	var req request.RegisterReq

	//2.绑定参数
	if err := ctx.ShouldBind(&req); err != nil {
		r.l.Error(err.Error())
		response.Error(ctx, response.InvalidParams, err.Error())
		return
	}

	//3.非空判断
	if strings.TrimSpace(req.UserName) == "" || strings.TrimSpace(req.Password) == "" {
		r.l.Error(errors.New("InvalidParams"))
		response.Error(ctx, response.InvalidParams, errors.New("InvalidParams").Error())
		return
	}

	//4.参数转换
	serviceReq := &request.ServiceRegisterReq{}
	if err := utils.Convert(&req, &serviceReq); err != nil {
		r.l.Error(err.Error())
		response.Error(ctx, response.InvalidParams, err.Error())
		return
	}

	//5.执行业务
	if err := r.t.Register(ctx.Request.Context(), serviceReq); err != nil {
		r.l.Error(err.Error())
		response.Error(ctx, response.ERROR, err.Error())
		return
	}

	//6.返回结果
	response.Ok(ctx, response.SUCCESS, response.GetMsg(response.SUCCESS))
}

func (r *V1) loginHandler(ctx *gin.Context) {

	//1.请求参数
	var req request.LoginReq

	//2.绑定参数
	if err := ctx.ShouldBind(&req); err != nil {
		r.l.Error(err.Error())
		response.Error(ctx, response.InvalidParams, response.GetMsg(response.InvalidParams))
		return
	}

	//3.非空判断
	if strings.TrimSpace(req.UserName) == "" || strings.TrimSpace(req.Password) == "" {
		r.l.Error(errors.New("InvalidParams"))
		response.Error(ctx, response.InvalidParams, response.GetMsg(response.InvalidParams))
		return
	}

	//4.参数转换
	serviceReq := &request.ServiceLoginReq{}
	if err := utils.Convert(&req, &serviceReq); err != nil {
		r.l.Error(err.Error())
		response.Error(ctx, response.InvalidParams, err.Error())
		return
	}

	//5.执行业务
	if resp, err := r.t.Login(ctx.Request.Context(), serviceReq); err != nil {
		r.l.Error(err.Error())
		response.Error(ctx, response.ERROR, err.Error())
		return
	} else {
		response.OkWithData(ctx, response.SUCCESS, response.GetMsg(response.SUCCESS), resp)
	}

}
